#
# "@(#) $Id: GetInfoDialog.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
from kio import *
from Utils.musicgenres import *
from Utils.human import *
from Utils.presets import *
from Utils.utils import *
from RatingWidget import *
from DB.Library import  Library
from Utils.backtick import backtick
import commands
from Utils.PListParser import PListReader
from PixmapPushButton import *
import Utils.amazon
from Utils.amazon import *
import Utils.crushToAscii
from Utils.crushToAscii import *
from ArtworkView import *

def fittedPixmap(pixmap,width,height):
	pixSize = pixmap.size()
	pw = pixSize.width()
	ph = pixSize.height()
	if pw==0: pw = 1
	if ph==0: ph = 1
	scaleX = 1.0*width/pw
	scaleY = 1.0*height/ph
	scale = scaleX
	if scaleX>scaleY:
		scale = scaleY
	if scale>1.0:
		scale = 1.0
	mat = QWMatrix()
	mat.scale(scale,scale)
	newpix = pixmap.xForm(mat)
	return newpix

def _get(a,b):
	if a==None:
		return b
	return a
"""
class ArtIconView(KIconView):
	_validExtensions = ['.jpg','.png']

	def __init__(self,container,name=''):
		KIconView.__init__(self,container,name)
		self.setAcceptDrops(True)
	
	def printFormats(self,event):
		print("formats:")
		n = 0
		while True:
			format = event.format(n)
			if (format==None):
				break
			print("  "+str(format))
			n = n+1

	def canImportFile(self,filePath):
		if os.path.exists(str(filePath)):
			if os.path.isdir(str(filePath)):
				return False
			else:
				ext = os.path.splitext(str(filePath))[1]
				if ext in self._validExtensions:
					return True
		return False

	def canImportFiles(self,uris):
		for uri in uris:
			if self.canImportFile(uri):
				return True
		return False

	def contentsDragEnterEvent(self,event):
		print "drag enter"
		if QUriDrag.canDecode(event):
			uris = QStringList()
			if QUriDrag.decodeLocalFiles(event,uris):
				if self.canImportFiles(uris):
					event.accept(True)

	def contentsDropEvent(self,event):
		print "dropped remote drag on art"
		uris = QStringList()
		if QUriDrag.decodeLocalFiles(event,uris):
			#uris = cleanup(uris)
			for uri in uris:
				pixmap=QPixmap(uri)
				item = QIconViewItem(self,"",pixmap)
				return
			#self.library.importFiles(removeDuplicates(uris),None)
"""
	
class GetInfoDialog(KDialogBase):
	_numbers = "0123456789"

	def __init__(self,track):
		self.track = track
		trackName = _get(self.track.title,'<untitled>')
		buttons = KDialogBase.Ok
		if not track.remote:
			buttons  = buttons + KDialogBase.Cancel
		KDialogBase.__init__(self,KDialogBase.Tabbed,trackName,buttons,KDialogBase.Ok,None,"getinfo",True)
		self.makeArtistCompletion()
		self.makeAlbumCompletion()
		self.lyricsJob = None
		self.add()
		self.load()
		self.adjustSize()
	
	def cleanup(self):
		if self.lyricsJob:
			self.lyricsJob = None
	
	def makeArtistCompletion(self):
		library = Library.mainLibrary()
		artists = library.artists()
		self.artistCompletion = KCompletion()
		self.artistCompletion.setOrder(KCompletion.Sorted)
		for artist in artists:
			self.artistCompletion.addItem(artist)
	
	def makeAlbumCompletion(self):
		library = Library.mainLibrary()
		albums = library.albums()
		self.albumCompletion = KCompletion()
		self.albumCompletion.setOrder(KCompletion.Sorted)
		for album in albums:
			self.albumCompletion.addItem(album)
		
	def add(self):
		if not self.track.remote and not self.track.player:
			self.addInfo()
		self.addSummary()
		if not self.track.remote and not self.track.player:
			if self.track.kind=='MPEG audio file':
				self.addArtwork()
			self.addLyrics()
	
	def load(self):
		self.loadSummary()
		if not self.track.remote and not self.track.player:
			self.loadInfo()
			if self.track.kind=='MPEG audio file':
				self.loadArtwork()
			self.loadLyrics()

	def unload(self):
		tags = {}
		self.unloadSummary(tags)
		if not self.track.remote and not self.track.player:
			self.unloadInfo(tags)
			if self.track.kind=='MPEG audio file':
				self.unloadArtwork()
			self.unloadLyrics(tags)
		return tags

	def addSummary(self):
		page = self.addPage(i18n("Summary"))
		layout = QVBoxLayout(page)
		self.addSummaryArtworkAndTitle(page,layout)
		self.addHDivider(page,layout)
		layout.addItem(QSpacerItem(1,1,QSizePolicy.Fixed,QSizePolicy.Expanding))
		self.addSummaryInfo(page,layout)
		layout.addItem(QSpacerItem(1,1,QSizePolicy.Fixed,QSizePolicy.Expanding))
		self.addHDivider(page,layout)
		self.addSummaryLocation(page,layout)

	def addSummaryArtworkAndTitle(self,container,containerLayout):
		layout = QHBoxLayout()
		containerLayout.addLayout(layout)
		self.addSummaryArtwork(container,layout)
		layout.addItem(QSpacerItem(5,1,QSizePolicy.Fixed,QSizePolicy.Fixed))
		self.addSummaryTitle(container,layout)
		#layout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Expanding))

	def getAlbumCover(self):
		data = self.track.image
		if data==None:
			return None
		pixmap = QPixmap()
		pixmap.loadFromData(data)
		return pixmap
		
	def addSummaryArtwork(self,container,containerLayout):
		self.artwork = QLabel("",container)
		self.artwork.setFrameStyle(QFrame.Box+QFrame.Plain)
		self.artwork.setLineWidth(1)
		self.artwork.setFixedSize(QSize(100,100))
		self.artwork.setPaletteBackgroundColor(QColor(255,255,255))
		self.artwork.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
		self.artwork.setAlignment(Qt.AlignCenter)
		containerLayout.addWidget(self.artwork)
	
	def addSummaryTitle(self,container,containerLayout):
		layout = QVBoxLayout()
		containerLayout.addLayout(layout)
		self.nameDuration =KSqueezedTextLabel(container)
		self.artist = QLabel("",container)
		self.album = QLabel("",container)
		layout.addWidget(self.nameDuration)
		layout.addWidget(self.artist)
		layout.addWidget(self.album)
		layout.addItem(QSpacerItem(1,1,QSizePolicy.Fixed,QSizePolicy.Expanding))

	def addSummaryInfo(self,container,containerLayout):
		layout = QHBoxLayout()
		containerLayout.addLayout(layout)
		grid = QGridLayout(7,2)
		layout.addLayout(grid)

		label = QLabel(i18n("<b>Kind:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,0,0)
		self.kind = QLabel("",container)
		grid.addWidget(self.kind,0,1)

		label = QLabel(i18n("<b>Size:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,1,0)
		self.fileSize = QLabel("",container)
		grid.addWidget(self.fileSize,1,1)

		label = QLabel(i18n("<b>Bit Rate:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,2,0)
		self.bitRate = QLabel("",container)
		grid.addWidget(self.bitRate,2,1)

		label = QLabel(i18n("<b>Sample Rate:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,3,0)
		self.sampleRate = QLabel("",container)
		grid.addWidget(self.sampleRate,3,1)

		label = QLabel(i18n("<b>Date Modified:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,4,0)
		self.modDate = QLabel("",container)
		grid.addWidget(self.modDate,4,1)

		label = QLabel(i18n("<b>Play Count:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,5,0)
		self.playCount = QLabel("",container)
		grid.addWidget(self.playCount,5,1)

		label = QLabel(i18n("<b>Last Played:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,6,0)
		self.lastPlayed = QLabel("",container)
		grid.addWidget(self.lastPlayed,6,1)

		layout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))

		grid = QGridLayout(7,2)
		layout.addLayout(grid)

		label = QLabel(i18n("<b>Format:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,0,0)
		self.format = QLabel("",container)
		grid.addWidget(self.format,0,1)

		label = QLabel(i18n("<b>Channels:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,1,0)
		self.channels = QLabel("",container)
		grid.addWidget(self.channels,1,1)

		label = QLabel(i18n("<b>ID3 Tag:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,2,0)
		self.id3tag = QLabel("",container)
		grid.addWidget(self.id3tag,2,1)

		label = QLabel(i18n("<b>Encoded with:</b>"),container)
		label.setAlignment(Qt.AlignRight)
		grid.addWidget(label,3,0)
		self.encoder = QLabel("",container)
		grid.addWidget(self.encoder,3,1)
		
	def addSummaryLocation(self,container,containerLayout):
		layout = QHBoxLayout()
		containerLayout.addLayout(layout)
		label = QLabel(i18n("<b>Where:</b>"),container)
		self.location = KSqueezedTextLabel(container)
		#self.location.setText(self.track.get("Location","<file not found>"))
		layout.addWidget(label)
		layout.addWidget(self.location)

	def loadSummary(self):
		pixmap = self.getAlbumCover()
		if pixmap:
			self.artwork.setText("")
			self.artwork.setPixmap(fittedPixmap(pixmap,100,100))
		else:
			self.artwork.setPixmap(QPixmap())
			self.artwork.setText(u"<font color='#C0C0C0'><b>%s</b></font>" % unikode(i18n("No Artwork<br>Available")))
		unknown = i18n('(unknown)')
		self.nameDuration.setText(self.track.title+"  ("+humanDuration(self.track.totalTime)+")")
		self.artist.setText(_get(self.track.artist,i18n("Unknown Artist")))
		self.album.setText(_get(self.track.album,i18n('Unknown Album')))
		self.kind.setText(_get(self.track.kind,unknown))
		self.fileSize.setText(humanFileSize(self.track.size))
		self.bitRate.setText(humanBitRate(self.track.bitRate))
		self.sampleRate.setText(humanSampleRate(self.track.sampleRate))
		self.modDate.setText(humanTimeStamp(self.track.dateModified))
		self.playCount.setText(str(self.track.playCount))
		self.lastPlayed.setText(humanTimeStamp(self.track.playDate))
		self.format.setText(_get(self.track.format,unknown))
		self.channels.setText(str(_get(self.track.mode,_get(self.track.channels,unknown))))
		self.id3tag.setText(_get(self.track.id3Version,unknown))
		self.encoder.setText(_get(self.track.encodedBy,unknown))
		if self.track.player:
			self.location.setText("iPod")
		else:
			self.location.setText(_get(self.track.location,i18n("(File Not Found)")))

	def unloadSummary(self,tags):
		pass

	def addInfo(self):
		page = self.addPage(i18n("Info"))
		layout = QVBoxLayout(page)
		self.addInfoItems(page,layout)

	def addInfoItems(self,container,containerLayout):
	
		tabLayout=QHBoxLayout(0,'tabView')
		containerLayout.addLayout(tabLayout,2)
		
		labelLayout=QVBoxLayout(5,'label')
		tabLayout.addLayout(labelLayout,2)

		inputLayout=QVBoxLayout(5,'input')
		tabLayout.addLayout(inputLayout,2)
	
		label = QLabel(i18n("<b>Name: </b>"),container)
		labelLayout.addWidget(label)
		
		self.nameEdit = KLineEdit("",container)
		inputLayout.addWidget(self.nameEdit)
		
		label = QLabel(i18n("<b>Artist: </b>"),container)
		labelLayout.addWidget(label)
		
		self.artistEdit = KLineEdit("",container)
		self.artistEdit.setCompletionObject(self.artistCompletion)
		inputLayout.addWidget(self.artistEdit)

		label = QLabel(i18n("<b>Album: </b>"),container)
		labelLayout.addWidget(label)
		
		self.albumEdit = KLineEdit("",container)
		self.albumEdit.setCompletionObject(self.albumCompletion)
		inputLayout.addWidget(self.albumEdit)
	
		label = QLabel(i18n("<b>Genre: </b>"),container)
		labelLayout.addWidget(label)

		gyLayout = QHBoxLayout()
		inputLayout.addLayout(gyLayout)

		self.genreEdit = KComboBox(False,container)
		sortedGenres = musicGenres[:]
		sortedGenres.sort()
		for genre in sortedGenres:
			self.genreEdit.insertItem(genre)
		gyLayout.addWidget(self.genreEdit,2)
	
		label = QLabel(i18n("<b>Year: </b>"),container)
		gyLayout.addWidget(label)
		
		self.yearEdit = QSpinBox(1900,2100,1,container,"yearEdit")
		self.yearEdit.setSpecialValueText(" ")
		QObject.connect(self.yearEdit,SIGNAL("valueChanged(int)"),self.changedTagYr)
		gyLayout.addWidget(self.yearEdit)
		gyLayout.insertSpacing(1,10)

		
		lineLabel1=QLabel(" ",container)
		lineLabel1.setFrameStyle(QFrame.HLine|QFrame.Sunken)
		inputLayout.addWidget(lineLabel1)
		spacer=QLabel(" ",container)
		labelLayout.addWidget(spacer)

		dtLayout=QHBoxLayout()
		inputLayout.addLayout(dtLayout,2)

		label = QLabel(i18n("<b>Track: </b>"),container)
		labelLayout.addWidget(label)
		
		tLayout=QHBoxLayout(0,'tntc')
		dtLayout.addLayout(tLayout,2)
		
		self.trackNumEdit = QSpinBox(0,1000,1,container,"trackNumEdit")
		QObject.connect(self.trackNumEdit,SIGNAL("valueChanged(int)"),self.changedTagTn)
		self.trackNumEdit.setSpecialValueText(" ")
		self.trackNumEdit.setMaximumWidth(100)
		tLayout.addWidget(self.trackNumEdit)
		label = QLabel(i18n(" of "),container)
		tLayout.addWidget(label)
		
		self.trackCountEdit = QSpinBox(0,1000,1,container,"trackCountEdit")
		self.trackCountEdit.setSpecialValueText(" ")
		self.trackCountEdit.setMaximumWidth(100)
		QObject.connect(self.trackCountEdit,SIGNAL("valueChanged(int)"),self.changedTagTc)
		tLayout.addWidget(self.trackCountEdit)

		layout = QHBoxLayout(0,'dndc')
		dtLayout.addLayout(layout)
		
		
		label = QLabel(i18n("<b>Disc:</b>"),container)
		layout.addWidget(label)

		
		self.discNumEdit = QSpinBox(0,1000,1,container,"discNumEdit")
		self.discNumEdit.setSpecialValueText(" ")
		QObject.connect(self.discNumEdit,SIGNAL("valueChanged(int)"),self.changedTagDn)
		layout.addWidget(self.discNumEdit)
		label = QLabel(i18n(" of "),container)
		layout.addWidget(label)
		self.discCountEdit = QSpinBox(0,1000,1,container,"discCountEdit")
		self.discCountEdit.setSpecialValueText(" ")
		QObject.connect(self.discCountEdit,SIGNAL("valueChanged(int)"),self.changedTagDc)
		layout.addWidget(self.discCountEdit)
		
		gcLayout=QHBoxLayout()
		inputLayout.addLayout(gcLayout,2)
		
		label = QLabel(i18n("<b>Grouping:</b>"),container)
		labelLayout.addWidget(label)
		
		self.groupingEdit = KLineEdit("",container)
		gcLayout.addWidget(self.groupingEdit)
		
		label = QLabel(i18n("<b>Composer: </b>"),container)
		labelLayout.addWidget(label)
		
		self.composerEdit = KLineEdit("",container)
		inputLayout.addWidget(self.composerEdit)

		label = QLabel(i18n("<b>Comment:</b>"),container)
		labelLayout.addWidget(label)
		self.commentEdit = KLineEdit(container)
		inputLayout.addWidget(self.commentEdit)
		
		#have to align things correctly
		labelPlaceHolder = QLabel(i18n("  "),container)
		labelLayout.addWidget(labelPlaceHolder)
		self.compilationEdit = QCheckBox(i18n("Part of a compilation"),container)
		inputLayout.addWidget(self.compilationEdit,1)
	
		lineLabel=QLabel("",container)
		lineLabel.setFrameStyle(QFrame.HLine|QFrame.Sunken)
		containerLayout.addWidget(lineLabel)
		
		#MusicBrainz 
		#don't show if file type is not supported
		kind=self.track.kind
		#print kind, "TRACK KIND"
		if kind == "MPEG audio file" or kind == 'Ogg audio file' or kind == 'WAV audio file':
			mbLayout=QHBoxLayout(10,'mb')
			containerLayout.addLayout(mbLayout,3)
			
			self.trmLookUpButton = QPushButton("Look up tags (with MusicBrainz)",container)
			mbLayout.addWidget(self.trmLookUpButton)
			QObject.connect(self.trmLookUpButton,SIGNAL("released()"),self.lookUpTags)
			
			mbLayout.insertSpacing(1,10)
		
			navLayout=QHBoxLayout(5,'nav')
			mbLayout.addLayout(navLayout,3)
			self.prevLookUpButton = SmallPixmapPushButton(QIconSet(QPixmap(art("buttonback.png"))),"",container) #QPushButton("Previous Match",container)
			navLayout.addWidget(self.prevLookUpButton)
			QObject.connect(self.prevLookUpButton,SIGNAL("released()"),self.prevLookUpTags)
			QToolTip.add(self.prevLookUpButton,i18n("Select previous match"))
			self.prevLookUpButton.hide()
			
			self.nextLookUpButton =  SmallPixmapPushButton(QIconSet(QPixmap(art("buttonforward.png"))),"",container) #QPushButton("Next Match",container)
			navLayout.addWidget(self.nextLookUpButton)
			QObject.connect(self.nextLookUpButton,SIGNAL("released()"),self.nextLookUpTags)
			QToolTip.add(self.nextLookUpButton,i18n("Select next match"))
			self.nextLookUpButton.hide()
			
	
			self.mbResultStat=QLabel("Original Tag",container)
			navLayout.addWidget(self.mbResultStat,3)
			self.mbResultStat.setAlignment(Qt.AlignCenter)
			
			self.revertLookUpButton =  SmallPixmapPushButton(QIconSet(QPixmap(art("buttonrevert.png"))),"",container) #QPushButton("Next Match",container)
			mbLayout.addWidget(self.revertLookUpButton)
			QObject.connect(self.revertLookUpButton,SIGNAL("released()"),self.revertLookUpTags)
			QToolTip.add(self.revertLookUpButton,i18n("Revert to Original"))
			self.revertLookUpButton.hide()

	def changedTagYr(self):
		self.yearChanged=True
	def changedTagTn(self):
		self.tNumChanged=True
	def changedTagTc(self):
		self.tCountChanged=True
	def changedTagDn(self):
		self.dNumChanged=True
	def changedTagDc(self):	
		self.dCountChanged=True
		
	def prevLookUpTags(self):
		self.mbTrackIndex-=1
		if self.mbTrackIndex<0:
			self.mbTrackIndex=len(self.qPlist)-1
		self.putMBTrackInfo(self.qPlist[self.mbTrackIndex])
		mbStatus=QString("Matching Tag ")
		mbStatus.append(QString.number(self.mbTrackIndex+1))
		mbStatus.append(i18n("/"))
		mbStatus.append(QString.number(len(self.qPlist)))
		self.mbResultStat.setText(mbStatus)
		
	def nextLookUpTags(self):
		self.mbTrackIndex+=1
		if self.mbTrackIndex>(len(self.qPlist)-1):
			self.mbTrackIndex=0
		self.putMBTrackInfo(self.qPlist[self.mbTrackIndex])
		mbStatus=QString("Matching Tag ")
		mbStatus.append(QString.number(self.mbTrackIndex+1))
		mbStatus.append(i18n("/"))
		mbStatus.append(QString.number(len(self.qPlist)))
		self.mbResultStat.setText(mbStatus)
		
	def revertLookUpTags(self):
		self.putMBTrackInfo(self.tagsBackup)
		mbStatus=QString("Original Tag")
	#	mbStatus.append(QString.number(len(self.qPlist)))
	#	mbStatus.append(" matches)")
		self.mbResultStat.setText(mbStatus)
		
	def lookUpTags(self):
		self.qPlist=None
		self.mbTrackIndex=0
		self.tagsBackup={}
		kind=self.track.kind
		if kind == "MPEG audio file":
			cmdline='trmxml'+commands.mkarg('-m')+commands.mkarg('-x')+commands.mkarg(self.track.location)
		elif kind == 'Ogg audio file':
			cmdline='trmxml'+commands.mkarg('-o')+commands.mkarg('-x')+commands.mkarg(self.track.location)
		elif kind == 'WAV audio file':
			cmdline='trmxml'+commands.mkarg('-w')+commands.mkarg('-x')+commands.mkarg(self.track.location)
		parser=PListReader()
		queryXML=backtick(cmdline)
		qResult=parser.parseString(queryXML)
		if qResult is not None and len(qResult) is not 0: 
			self.qPlist=qResult[0]
			if self.qPlist is not None and len(self.qPlist) is not 0:
				self.putMBTrackInfo(self.qPlist[self.mbTrackIndex],True)	
				mbStatus=QString("Matching Tag ")
				mbStatus.append(QString.number(self.mbTrackIndex+1))
				mbStatus.append(i18n("/"))
				mbStatus.append(QString.number(len(self.qPlist)))
				self.mbResultStat.setText(mbStatus)
				self.nextLookUpButton.show()
				self.prevLookUpButton.show()
				self.revertLookUpButton.show()
			else: 
				KMessageBox.error(self,"8traK could not find tag information about this track","Tag Info not Found")
		else: 
			KMessageBox.error(self,"8traK could not find tag information about this track","Tag Info not Found")

	def putMBTrackInfo(self,MBtrack=None,originalTags=False):
		if MBtrack is not None and len(MBtrack) > 0:
			if MBtrack.has_key('Name'):
				if originalTags: self.tagsBackup['Name']=self.nameEdit.text()
				self.nameEdit.setText(MBtrack['Name'])
			if MBtrack.has_key('Artist'):
				if originalTags: self.tagsBackup['Artist']=self.artistEdit.text()
				self.artistEdit.setText(MBtrack['Artist'])
			if MBtrack.has_key('Album'):
				if originalTags: self.tagsBackup['Album']=self.albumEdit.text()
				self.albumEdit.setText(MBtrack['Album'])
			if MBtrack.has_key('Genre'):
				if originalTags: self.tagsBackup['Genre']=self.genreEdit.getCurrentText()
				self.genreEdit.setCurrentText(MBtrack['Genre'])
			if MBtrack.has_key('Year'):
				if originalTags: self.tagsBackup['Year']=str(self.yearEdit.text()).strip
				try: self.yearEdit.setValue(int(MBtrack['Year']))
				except: self.yearEdit.setValue(0)
			if MBtrack.has_key('TrackNum'):	
				if originalTags: self.tagsBackup['TrackNum']=str(self.trackNumEdit.text()).strip()
				try: self.trackNumEdit.setValue(int(MBtrack['TrackNum']))
				except: self.trackNumEdit.setValue(0)
			if MBtrack.has_key('TrackCount'):	
				if originalTags: self.tagsBackup['TrackCount']=str(self.trackCountEdit.text()).strip()
				try: self.trackCountEdit.setValue(int(MBtrack['TrackCount']))
				except: self.trackCountEdit.setValue(0)
			if MBtrack.has_key('DiscNum'):	
				if originalTags: self.tagsBackup['DiscNum']=str(self.discNumEdit.text()).strip()
				try: self.discNumEdit.setValue(int(MBtrack['DiscNum']))
				except: self.discNumEdit.setValue(0) 
			if MBtrack.has_key('DiscCount'):	
				if originalTags: self.tagsBackup['DiscCount']=str(self.discCountEdit.text()).strip()
				try: self.discCountEdit.setValue(int(MBtrack['DiscCount']))
				except: self.discCountEdit.setValue(0)
			self.MBedit=True
		
		
	def loadInfo(self):
		if self.track.title: self.nameEdit.setText(self.track.title)
		if self.track.artist: self.artistEdit.setText(self.track.artist)
		if self.track.album: self.albumEdit.setText(self.track.album)
		if self.track.grouping: self.groupingEdit.setText(self.track.grouping)
		if self.track.composer: self.composerEdit.setText(self.track.composer)
		if self.track.comment: self.commentEdit.setText(self.track.comment)
		if self.track.genre: self.genreEdit.setCurrentText(self.track.genre)
		if self.track.year: self.yearEdit.setValue(_get(self.track.year,0))
		#self.trackNumEdit.setValue(_get(self.track.trackNum,0))
		#tc=_get(self.track.trackCount,0)
		#self.trackCountEdit.setValue(tc)
		#self.discNumEdit.setValue(_get(self.track.discNum,0))
		#dc=_get(self.track.discCount,0)
		#self.discCountEdit.setValue(dc)
		#self.compilationEdit.setChecked(_get(self.track.compilation,False))
		self.yearChanged=False
		self.tNumChanged=False
		self.tCountChanged=False
		self.dNumChanged=False
		self.dCountChanged=False
		self.MBedit=False

	def unloadInfo(self,tags):
		tags['title'] = unikode(self.nameEdit.text())
		if unikode(self.artistEdit.text())!=self.track.artist or self.MBedit: tags['artist'] = unikode(self.artistEdit.text())
		if unikode(self.albumEdit.text())!=self.track.album or self.MBedit: tags['album'] = unikode(self.albumEdit.text())
		if self.groupingEdit.edited(): tags['grouping'] = unikode(self.groupingEdit.text())
		if self.composerEdit.edited(): tags['composer'] = unikode(self.composerEdit.text())
		if self.track.genre!= str(self.genreEdit.currentText()) or self.MBedit:
			tags['genre'] = str(self.genreEdit.currentText())
		if self.commentEdit.isModified(): tags['comment'] = unikode(self.commentEdit.text())
		if self.yearChanged or self.MBedit: 
			if str(self.yearEdit.text()).strip() is '':
				tags['year'] = 0
			else:	tags['year'] = str(self.yearEdit.text()).strip()
		if self.tNumChanged or self.MBedit: 
			print str(self.trackNumEdit.text()), "ZZZZZZZZZZ", self.trackNumEdit.text()
			if str(self.trackNumEdit.text()).strip() is '':
				tags['trackNum'] = 0
			else:	tags['trackNum'] = str(self.trackNumEdit.text()).strip()
		if self.tCountChanged: 
			if str(self.trackCountEdit.text()).strip() is '':
				tags['trackCount'] = 0
			else:	tags['trackCount'] = str(self.trackCountEdit.text())
		if self.dNumChanged: 
			if str(self.discNumEdit.text()).strip() is '':
				tags['discNum'] = 0
			else:	tags['discNum'] = str(self.discNumEdit.text()).strip()
		if self.dCountChanged: 
			if str(self.discCountEdit.text()).strip() is '':
				tags['discCount'] = 0
			else: 	tags['discCount'] = str(self.discCountEdit.text()).strip()
		if self.compilationEdit.isChecked() != self.track.compilation:
			tags['compilation']=self.compilationEdit.isChecked()

		
	def addArtwork(self):
		page = self.addPage(i18n("Artwork"))
		layout = QVBoxLayout(page)
		self.addArtworkItems(page,layout)
		layout.setSpacing(10)

	def addArtworkItems(self,container,containerLayout):
		#self.artIconView = ArtworkView(container,"")
		#self.artView=QFrame(container)
		self.artworkView=ArtworkView(container,'artview',container,self.track,False)
		containerLayout.addWidget(self.artworkView)
		hbox = QHBoxLayout()
		hbox.setSpacing(5)
		containerLayout.addLayout(hbox)
##		self.addButton = QPushButton(i18n("Add..."),container)
##		hbox.addWidget(self.addButton)
		self.deleteButton = QPushButton(i18n("Remove"),container,'remBtn')
		QObject.connect(self.deleteButton,SIGNAL('released()'),self.removeArt)
		hbox.addWidget(self.deleteButton)
		self.amazonLookUpButton = QPushButton(i18n("Fetch Art from Amazon.com"),container)
		hbox.addWidget(self.amazonLookUpButton)
		QObject.connect(self.amazonLookUpButton,SIGNAL("released()"),self.amazonLookUp)
		hbox.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		#self.sizeSlider = QSlider(Qt.Horizontal,container)
		#hbox.addWidget(self.sizeSlider)
	
	def removeArt(self):
		#self.artIconView.clear()
		self.artworkView.setDefault()
		#self.track.image=None
		self.delOnUnload=True
		self.deleteButton.setEnabled(False)
		self.albumCover=None
	
	def amazonLookUp(self):
		setLicense('D3523Y3ZHA0AZ5')
		skip=False
		if self.track.compilation:
			skip=True
		srchStr=unikode(self.albumEdit.text())+" "+unikode(self.artistEdit.text())
		if srchStr=='':
			KMessageBox.error(self,i18n("Please provide album name in order to lookup album art"),i18n("No album name given"))
			return
		try:
			(pixmap,imgurl)=getAlbumArt(srchStr,'large')
		except:
			if self.artistEdit.text()!='' and not skip:
				try:
					srchStr=unikode(self.albumEdit.text())
					(pixmap,imgurl)=getAlbumArt(srchStr,'large')
				except:
					pixmap=None
					KMessageBox.error(self,i18n("8traK could not find any artwork for this artist/album"),i18n("No artwork available"))
			else:		
				pixmap=None
				KMessageBox.error(self,i18n("8traK could not find any artwork for this artist/album"),i18n("No artwork available"))
		if pixmap!= None:
			#data=open(resArt[0])
		#	print resArt
		#	pixmap =  QPicture()
			#pixmap=QPixmap(resArt[0])
			#self.artIconView.clear()
			#item = QIconViewItem(self.artIconView,"",pixmap)
			self.artworkView.setImg(pixmap)
			f=open(imgurl)
			self.albumCover=f.read()
			f.close()
			self.deleteButton.setEnabled(True)
			self.artwork.setText("")
			self.artwork.setPixmap(fittedPixmap(pixmap,100,100))
	
	def loadArtwork(self):
		pixmap = self.getAlbumCover()
		self.artworkView.setImg(pixmap)
		if pixmap:
			self.deleteButton.setEnabled(True)
		else:
			self.deleteButton.setEnabled(False)
		self.albumCover=None
		self.delOnUnload=False

	def unloadArtwork(self):
		if self.albumCover!=None or self.delOnUnload:
			self.track.image=self.albumCover

	def addLyrics(self):
		page = self.addPage(i18n("Lyrics"))
		layout = QVBoxLayout(page)
		self.addLyricsItems(page,layout)

	def addLyricsItems(self,container,containerLayout):
		label = QLabel(i18n("<b>Lyrics:</b>"),container)
		containerLayout.addWidget(label)
		self.lyricsEdit = QTextEdit(container)
		containerLayout.addWidget(self.lyricsEdit)
		hlayout = QHBoxLayout()
		hlayout.setSpacing(5)
		containerLayout.addLayout(hlayout)
		self.searchLyricsItem = QPushButton(container)
		self.searchLyricsItem.setText(i18n("Search the web..."))
		QObject.connect(self.searchLyricsItem,SIGNAL("released()"),self.hitSearchLyrics)
		hlayout.addWidget(self.searchLyricsItem)
		self.lyricsStatus = QLabel("",container)
		hlayout.addWidget(self.lyricsStatus)
	
	def hitSearchLyrics(self):
		artist = unikode(self.artistEdit.text())
		title = unikode(self.nameEdit.text())
		album = unikode(self.albumEdit.text())
		url = QString( "http://lyrc.com.ar/en/tema1en.php?artist=%1&songname=%2" ).arg(
			KURL.encode_string_no_slash( crush(artist) ),
			KURL.encode_string_no_slash( crush(title) ) )
		#print url
		self.lyricsJob = KIO.get(KURL(url),False,False)
		self.lyricsJob.suspend()
		self.lyricsData = ""
		QObject.connect(self.lyricsJob,SIGNAL('data(KIO::Job *,const QByteArray &)'),self.onLyricsData)
		QObject.connect(self.lyricsJob,SIGNAL('result(KIO::Job *)'),self.onLyricsResult)
		self.lyricsJob.resume()
		self.lyricsStatus.setText(i18n("<i>Searching...</i>"))
		self.searchLyricsItem.setEnabled(False)

	def onLyricsData(self,job,bytes):
		self.lyricsData = self.lyricsData+unikode(QString(bytes))

	def onLyricsResult(self,job):
		self.validLyrics = False
		if len(self.lyricsData)>0:
			lyrics = QString(self.lyricsData)
			lyrics.replace( QRegExp("<[aA][^>]*>[^<]*</[aA]>"), QString.null ) # remove links
			lyrics.replace( QRegExp("<[iI][mM][gG][^>]*>"), QString.null ) # remove images
			if lyrics.find( "<font size='2'>" ) != -1:
				lyrics = lyrics.mid( lyrics.find( "<font size='2'>" ) )
				lyrics = lyrics.mid( lyrics.find('</font>')+11) # nuke header
				if lyrics.find( "<p><hr" ) != -1:
					lyrics = lyrics.mid( 0, lyrics.find( "<p><hr" ) )
				else:
					lyrics = lyrics.mid( 0, lyrics.find( "<br /><br />" ) )
				lyrics.replace( QRegExp("\[\d\d\:\d\d\.\d\d\]"), QString.null) # nuke timestamps
				lyrics.replace( QRegExp("<br />"),QString.null) # nuke line endings
				lyrics = lyrics.mid(0,lyrics.find("<br>")) # nuke any trailing html fragments
				self.validLyrics = True
				self.lyricsEdit.setText(unikode(lyrics))
				self.lyricsStatus.setText("")
			elif lyrics.find( "Suggestions : " ) != -1 :
				self.lyricsStatus.setText(i18n("<i>Lyrics not found</i>"))
		else:
			self.lyricsStatus.setText(i18n("<i>Cannot reach lyrics service</i>"))
		self.lyricsJob = None
		self.searchLyricsItem.setEnabled(True)

	def loadLyrics(self):
		self.validLyrics = False
		try:
			self.lyricsEdit.setText(self.track.lyrics)
			self.validLyrics = True
		except: pass
	
	def unloadLyrics(self,tags):
		if self.validLyrics and self.track.lyrics!=unikode(self.lyricsEdit.text()):
			tags['lyrics'] = unikode(self.lyricsEdit.text())

	def addHDivider(self,container,containerLayout):
		containerLayout.addItem(QSpacerItem(1,2,QSizePolicy.Expanding,QSizePolicy.Fixed))
		w = QWidget(container)
		w.setPaletteBackgroundColor(QColor(0,0,0))
		w.setFixedHeight(1)
		w.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed)
		containerLayout.addItem(QSpacerItem(1,2,QSizePolicy.Expanding,QSizePolicy.Fixed))
		containerLayout.addWidget(w)
